<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\service\AdminUserService;
use think\Model;

//管理员用户数据表
class AdminUserModel extends Model
{
    public $error = '';

    protected $table = 'utf8mb4_admin_user';

    public $rule = [
        'username' => 'require|max:10|unique:utf8mb4_admin_user',
        'name' => 'require|max:10',
        'phone' => 'require|mobile|unique:utf8mb4_admin_user',
        'email' => 'email',
        'role_id' => 'require|number',
        'password' => 'require|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/',
        'password1' => 'require|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\W]{6,18}$/',
    ];

    public $message = [
        'username.require' => '登录名不能为空',
        'username.max' => '登录名最长10个字符',
        'username.unique' => '登录名已经存在',
        'name.require' => '名称不能为空',
        'name.max' => '名称最长10个字符',
        'phone.require' => '手机号不能为空',
        'phone.mobile' => '手机号格式不正确',
        'phone.unique' => '手机号已经存在',
        'email.email' => '邮箱格式不正确',
        'role_id.require' => '必须选择角色',
        'role_id.number' => '角色选择错误',
        'password.require' => '密码必须填写',
        'password.regex' => '密码长度为6到18,且必须包含字母和数字',
        'password1.require' => '确认密码必须填写',
        'password1.regex' => '确认密码长度为6到18,且必须包含字母和数字',
    ];

    /*
     * @title 检测和创建密码
     * @param array $param 后台请求的参数数组
     * @return bool
     * */
    public function createPassword(array &$param): bool
    {
        if ($param['password'] != $param['password1']) {
            $this->error = '2次输入密码不一致';
            return false;
        }
        $salt = rand_str(5);
        $pass = AdminUserService::ins()->createPassword($param['password'], $salt);
        $param['password'] = $pass;
        $param['salt'] = $salt;
        unset($param['password1']);
        return true;
    }

}